package com.mw.controller;

import com.mw.domain.Comment;
import com.mw.domain.News;
import com.mw.domain.User;
import com.mw.service.CommentService;
import com.mw.service.NewsService;
import com.mw.service.UserService;
import com.mw.util.StringTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/comment")
public class CommentController {
    @Autowired
    NewsService newsService;
    @Autowired
    CommentService commentService;
    @Autowired
    UserService userService;

    /**
     * 添加评论
     * @param request
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String addComment(HttpServletRequest request){
        Comment comment = new Comment();
        User user = (User) request.getSession().getAttribute("user");
        String context = request.getParameter("context");
        if(context.startsWith("@")){
            //下两句截取@到：
            String tname = context.substring(1);
            tname = StringUtils.substringBefore(tname,":");

            User tUser = userService.getUserByUsername(tname);
            comment.setTid(Integer.toString(tUser.getId()));
            //去掉回复中的@XXX：，留下内容
            context = context.replaceFirst("@"+tname+":","");
        }else{
            //用户喜好加分
            News news = newsService.getNewsById(Integer.parseInt(request.getParameter("nid")));
            StringTool stringTool = new StringTool();
            user.setPreference(stringTool.typeAdd(user.getPreference(),news.getType(),2));
            userService.saveUser(user);
        }
        comment.setContext(context);
        comment.setUid(Integer.toString(user.getId()));
        comment.setNid(request.getParameter("nid"));
        commentService.saveComment(comment);

        return "redirect:/"+request.getParameter("nid");
    }

    /**
     * 删除评论
     * @param request
     * @return
     */
    @RequestMapping(value = "/del",method = RequestMethod.POST)
    public String delComment(HttpServletRequest request){
        String id = request.getParameter("id");
        commentService.delComment(Integer.valueOf(id));
        User user = (User)request.getSession().getAttribute("user");
        return "redirect:/user/"+user.getId();
    }
}
